const app = getApp()
import {
  getGoodsList,
  getShopInfo
} from '../../api/user'

import {
  getRandomIndex
} from '../../utils/util'


let currentPage = 1
let showCount = 10
let totalPage = 1
Page({
  data: {
    list: [],
    banner: []
  },
  onLoad(options) {

  },
  onShow() {
    this.initList()
    this.getShopInfo();
  },
  onReachBottom() {
    if (currentPage >= totalPage) {
      wx.showToast({
        title: '没有更多了',
        icon: 'none'
      })
      return
    }
    currentPage++
    this.fetchList()
  },
  onShareAppMessage() {
    const {
      banner
    } = this.data
    const targetImg = banner[getRandomIndex(0, banner.length)]
    let tenantId = wx.getStorageSync('tenantId')
    let shareId = wx.getStorageSync('shareId')
    let path = '/pages/index/index?a=1';

    if (tenantId) {
      path += `&tenantId=${tenantId}`
    }
    if (shareId) {
      path += `&shareId=${shareId}`
    }
    console.log(path)
    const imageUrl = targetImg.img_url || ''
    return {
      title: `${wx.getStorageSync('shop_name')}`,
      imageUrl,
      path,
    }
  },
  //#region  方法
  initList() {

    totalPage = 1
    currentPage = 1
    this.fetchList(true)
  },
  fetchList(init) {

    getGoodsList({
      currentPage,
      showCount,
    }).then(res => {
      console.log(res)

      const {
        list,
        totalPage: total
      } = res.data
      if (total) {
        totalPage = total
      }
      list.forEach((item, index) => {
        item.id = index
        if (item.pic) {
          item.picUrl = item.pic.split(',')[0]
        } else {
          item.picUrl = ''
        }

      })
      if (init) {
        this.setData({
          list: list
        })
      } else {
        this.setData({
          list: this.data.list.concat(list)
        })
      }
    }).catch((err) => {
      wx.showToast({
        title: '店铺信息获取失败！点击右上角重新进入小程序!',
        icon: 'none',
        duration: 10000,
      })
    })
  },
  getShopInfo() {

    getShopInfo({}).then(res => {
      console.log(res)
      this.setData({
        banner: res.data.banner_list
      })
      wx.setStorageSync('shop_name', res.data.tenantInfo.name || res.data.name)
      // 如果店铺信息不存在提示用户重新进入小程序
      // 店铺信息：res.data.tenantInfo.tenantId
      if(!res.data?.tenantInfo?.tenantId) {
        wx.showToast({
          title: '店铺信息获取失败！点击右上角重新进入小程序!',
          icon: 'none',
          duration: 10000,
        })
      }
    }).catch(() => {
      wx.showToast({
        title: '店铺信息获取失败！点击右上角重新进入小程序!',
        icon: 'none',
        duration: 10000,
      })
    })
  }
})